// subpkg/addPost/addPost.js
const util = require('../../utils/util')
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '',
    content: '',
    imageFileList: [],
    allFileList:[],
    // cloudPath: [],
    // envId: '',
    checked: false,
    addBtn: true,
    putType: '卖出',
    ddIndex: '',
    jyIndex: '',
    flIndex: '',
    price: '',
    _id: '',
  },

  // 文件读取完成后触发，event.detail.file: 当前读取的文件，再上传到图片服务器上
  afterRead(event) {
    const { file } = event.detail //获取所需要上传的文件列表
    const newFileList = file.map(item => ({ url: item.url }));
    this.setData({
      allFileList: this.data.allFileList.concat(file),
      imageFileList: this.data.imageFileList.concat(newFileList)
    });
  },
  // 上传
  putImg() {
    if (!this.data.title) {
      Toast('请输入标题！');
      return;
    }
    if (!this.data.content) {
      Toast('请输入内容！');
      return;
    }
    if (!this.data.price) {
      Toast('请输入价格！');
      return;
    }
    if (!this.data.ddIndex) {
      Toast('请选择地点！');
      return;
    }
    if (!this.data.flIndex) {
      Toast('请选择分类！');
      return;
    }
    if (!this.data.jyIndex) {
      Toast('请选择交易形式！');
      return;
    }
    if (!this.data.addBtn) {
      console.log('nononono')
      return
    }
    if (this.data.allFileList.length == 0) {
      console.log('没有图片')
      // this.putPost([])
      Toast('请上传至少一张图片！');
      return
    }
    Dialog.confirm({
      title: '温馨提示',
      message: '是否发布',
    })
      .then(() => {
        
        console.log('this.data.allFileList', this.data.allFileList)
        let oldfile = []
        let file = []
        this.data.allFileList.forEach(item => {
          if (item.url.includes('cloud://')) {
            console.log('旧图片')
            oldfile.push(item)
          } else {
            console.log('新图片')
            file.push(item)
          }
        })
        console.log('file', file)
        console.log('oldfile', oldfile)

        wx.showLoading({
          title: '上传中...'
        })
        this.setData({
          addBtn: false
        })
        wx.cloud.init();
        const uploadTasks = file.map(fileItem => this.uploadFilePromise(fileItem));
        Promise.all(uploadTasks)
          .then(data => {
            const newFileList = data.map(item => ({ url: item.fileID }));
            console.log('newFileList', newFileList)
            let l = oldfile.concat(newFileList)
            console.log('llll', l)
            this.putPost(l)
          })
          .catch((e) => {
            console.log('e', e)
              //存在有上传失败的文件
              wx.hideLoading()
              wx.showToast({
                title: '上传失败！',
                icon: 'none',
              })
              this.setData({
                addBtn: true
              })
          });

      })
      .catch(() => {
        // on cancel
      });

    
  },
  //封装上传图片函数,利用小程序云开函数
  uploadFilePromise(fileItem) {
    // TODO:优化-带上用户标示作为区分
    const imageName = fileItem?.url.slice(11, -4).slice(0,6);
    console.log(`imageName`, imageName)
    console.log(`fileItem.url`, fileItem.url)
    return wx.cloud.uploadFile({
      // 指定上传到的云路径
      cloudPath: `productImg/${imageName}.png`,
      // 指定要上传的文件的小程序临时文件路径
      filePath: fileItem.url,
    });
  },
  putPost(newFileList) {
    let t = new Date()
    let obj = {
      openid: wx.getStorageSync('openid'),
      creatTime: util.formatTime(t),
      time: t.getTime(),
      title: this.data.title,
      content: this.data.content,
      price: parseInt(this.data.price),
      school: this.data.ddIndex,
      deal: this.data.jyIndex,
      classify: this.data.flIndex,
      proType: this.data.putType,
      likeList: [],
      imgList: newFileList,
    }
    console.log('obj', obj)
    // return
    wx.cloud.callFunction({
      // 需调用的云函数名
      name: 'quickstartFunctions',
      // 传给云函数的参数
      data: {
        type: 'putProduct',
        obj: obj,
        _id: this.data._id
      },
    }).then((resp) => {
      console.log('resp',resp)
      wx.hideLoading()
      wx.showToast({ title: '发布成功', icon: 'none' });
      wx.switchTab({
        url: '../../pages/user/index'
      })
    }).catch((e) => {
      console.log(e)
      this.setData({
        addBtn: true
      })
    });
  },
  imageDelete(e) {
    // 删除
    console.log('e', e.detail)
    let newFileList = []
    let newAllFileList = []
    this.data.imageFileList.forEach((item, index) => {
      if (index != e.detail.index) {
        newFileList.push(item)
      }
    })
    this.data.allFileList.forEach((item, index) => {
      if (index != e.detail.index) {
        newAllFileList.push(item)
      }
    })
    this.setData({ 
      imageFileList: newFileList,
      allFileList: newAllFileList,
    });
  },
  setDDIndex(e) {
    this.setData({
      ddIndex: e.currentTarget.dataset.index,
    })
  },
  setJYIndex(e) {
    this.setData({
      jyIndex: e.currentTarget.dataset.index,
    })
  },
  setFLIndex(e) {
    this.setData({
      flIndex: e.currentTarget.dataset.index,
    })
  },
  inputChange: function(e) {
    let value = this.validateNumber(e.detail.value)
		this.setData({//setData是一个用来更新页面数据的函数
			price: value//e.detail.value表示输入框的当前值
		})
  },
  // 过滤，只取数字
  validateNumber(val) {
    return val.replace(/\D/g, '')
  },
  sx() {
    Dialog.confirm({
      title: '温馨提示',
      message: '是否重置内容',
    })
      .then(() => {
        this.setData({
          title: '',
          content: '',
          price: '',
          ddIndex: '',
          jyIndex: '',
          flIndex: '',
          imageFileList: [],
          allFileList:[],
        })
      })
      .catch(() => {
        // on cancel
      });

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('options', options.type)
    if (options.obj) {
      wx.setNavigationBarTitle({
        title: '修改商品',
      })
      let obj = JSON.parse(decodeURIComponent(options.obj))
      this.setData({
        title: obj.title,
        content: obj.content,
        price: obj.price,
        ddIndex: obj.school,
        jyIndex: obj.deal,
        flIndex: obj.classify,
        imageFileList: obj.imgList,
        allFileList: obj.imgList,
        putType: obj.proType,
        _id: obj._id
      })
    } else {
      this.setData({
        putType: options.type
      })
      wx.setNavigationBarTitle({
        title: '提交商品',
      })
    }


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})